<!doctype html>
<html>

<head>
    <title>Socket.IO chat</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font: 13px Helvetica, Arial;
        }

        div {
            background: #000;
            padding: 3px;
            position: fixed;
            bottom: 0;
            width: 100%;
        }

        div input {
            border: 0;
            padding: 10px;
            width: 90%;
            margin-right: .5%;
        }

        div button {
            width: 9%;
            background: rgb(130, 224, 255);
            border: none;
            padding: 10px;
        }

        #messages {
            list-style-type: none;
            margin: 0;
            padding: 0;
        }

        #messages li {
            padding: 5px 10px;
        }

        #messages li:nth-child(odd) {
            background: #eee;
        }

        p {
            padding: 5px 10px;
        }
    </style>
</head>

<body>
    <p id="onlineUser">在线人数:0</p>
    <ul id="messages"></ul>

    <div id="my_id" style="bottom:40px;background:none">
        自己id为：<span></span>
        <input style="width: 220px;border: 1px solid red;" id="uid" autocomplete="off" placeholder="请填写对方id" />
    </div>
    <div action="">
        <input id="m" autocomplete="off" /><button>Send</button>
    </div>
    <script src="https://cdn.socket.io/socket.io-1.4.0.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        var myName = false;
        var my_id = Math.round(Math.random() * 10);
        $("#my_id span").text(my_id);
        var socket = io('http://localhost:3001', {
            secure: true,
            query: { uid: my_id }
        });
        socket.on('open', function () {
            $('#messages').append($('<li>').text('已连接至服务器,请输入昵称'));
        });
        //监听服务端的message事件，接受每一条消息
        socket.on('message', function (json) {
            $('#messages').append($('<li>').text(json));
        });
        $('button').click(function () {
            if (!$('#m').val() || !$("#my_id span").text()) return;
            socket.emit('message', { uid: $("#uid").val(), msg: $('#m').val() });
            $("#m").val("")
        })
    </script>
</body>

</html>